import React from 'react';
import { connect } from 'dva';
import styles from './laundry_submit.less';
import styles1 from './laundry_submit.css';
import { addSessionData ,getSessionData,getData } from '../../../utils/localData'
import { API_HOST , getAgentsId} from '../../../settings'
import axios from '../../../utils/axiosUtil'
import {add,mul} from '../../../utils/MyMath'
import { isIOS } from '../../../utils/isAS'
import TimeBox from './timeBox/timeBox.js'
import { NavBar, Icon, List, Accordion,TextareaItem  } from 'antd-mobile'
import moment from 'moment'
const Item = List.Item;
@connect(({global,orders}) => ({
  global,orders
}))
export default class Laundry_submit extends React.Component {
  constructor() {
    super()
    this.state = {
      timeBoxShow:false,
      checkDate:'',
      checkTime:'',
      panelText:'',
      remark:'',
      userAddress:false,
      remarkShow:false
    }
  }

  renderDate(weekDay){
    let date = moment(weekDay).format("MM-DD");
    let week = "";
    switch (moment(weekDay).format("d")) {
      case "0":
        week = "（周日）"
        break;
      case "1":
        week = "（周一）"
        break;
      case "2":
        week = "（周二）"
        break;
      case "3":
        week = "（周三）"
        break;
      case "4":
        week = "（周四）"
        break;
      case "5":
        week = "（周五）"
        break;
      case "6":
        week = "（周六）"
        break;
      default:
        break;
    }
    return date+week;
  }

  render() {
    document.title = "提交订单"
    console.log(this.props.orders)
    if(this.props.orders.payOrderId){
      alert(this.props.orders.orderNum)
    }

    let {deliveryFee} = this.props.location
    this.state.checkDate = getSessionData("checkDate")
    this.state.checkTime = getSessionData("checkTime")
    this.state.userAddress = JSON.parse(getSessionData("userAddress"))
    if(deliveryFee){
      addSessionData("shop-dd-fee",deliveryFee)
    }else{
      deliveryFee = JSON.parse(getSessionData("shop-dd-fee"))
    }
    let {shops} = this.props.location
    if(shops){
      addSessionData("shop-dd-shops",shops)
    }else{
      shops = JSON.parse(getSessionData("shop-dd-shops"))
    }
    let panelTextSS = "有问题请填写备注"
    if(this.state.panelText.length>0){
      panelTextSS = this.state.panelText.length>8?this.state.panelText.substr(0,8)+"...":this.state.panelText
    }
    let shengyu = ""
    let sumM = 0
    let count = 0
    let imgs = []
    //console.log(shops)
    if(shops){
      shops.forEach((item,index)=> {
        //熏染图片不超过3张
        if(index <= 2){
          imgs.push(<img key={index} src={item.commodityImgUrl} alt='' className={styles.sub_img} />)
        }
        //总价
        sumM = add(mul(item.buyNum,item.currentPrice),sumM)
        count  += item.buyNum
      });
    }
    shengyu = count
    return (
     <div className={styles.sub_all}>
      {this.state.timeBoxShow?<TimeBox timeBoxHide={()=>{
        this.setState({timeBoxShow:false})
      }} check={(date,time)=>{
        addSessionData("checkDate",date)
        addSessionData("checkTime",time)
        this.setState({
          checkDate:date,
          checkTime:time,
          timeBoxShow:false
        })
      }}/>:null}

      <div className={styles1.sub_top}>

        <div className={styles.sub_one}>
          <img src={'./img/addr.png'} className={styles.sub_border} alt=""/>
           <List className="my-list">
              {this.state.userAddress?
              <div className={styles.sub_litss}
              onClick={() => {
                  console.log("获取定位的代理商id=》"+getAgentsId())
                  window.YLJsBridge.call(
                      'selectAddress',
                      {agentId:getAgentsId()},
                      (data)=>{
                        console.log(data)
                        if(data.code==0){
                          addSessionData("userAddress",JSON.parse(data.value))
                          this.setState({userAddress:JSON.parse(data.value)})
                        }
                      }
                  )
              }}>
                  <div className={styles.sub_litinss}>
                    <div>
                      <span className={styles.sub_litspan}>{this.state.userAddress.name}</span>
                      <span className={styles.sub_litspan}>{this.state.userAddress.gender}</span>
                      <span>{this.state.userAddress.mobile}</span>
                    </div>
                    <div className={styles.sub_litsadd}>{this.state.userAddress.address.substr(0,13)+'...'}
                    </div>
                  </div>
                  <img src={'./img/in.png'} className={styles.sub_inimg} alt=""/>
                  {/*<Icon type="right" color={"#C7C7C7"} size={"s"}/>*/}
              </div>
              :
              <div className={styles.sub_lit}
                onClick={() => {
                  console.log("获取定位的代理商id=》"+getAgentsId())
                  window.YLJsBridge.call(
                      'selectAddress',
                      {agentId:getAgentsId()},
                      (data)=>{
                        console.log(data)
                        if(data.code==0){
                          addSessionData("userAddress",JSON.parse(data.value))
                          this.setState({userAddress:JSON.parse(data.value)})
                        }
                      }
                  )
              }}>
                  <div className={styles.sub_litin}>请选取/送衣地址</div>
                  <img src={'./img/in.png'} className={styles.sub_inimg} alt=""/>
                  {/*<Icon type="right" color={"#C7C7C7"} size={"s"}/>*/}
              </div>
              }
              {this.state.checkDate && this.state.checkTime ?
                <div className={styles.sub_litss2} onClick={() => {
                    this.setState({timeBoxShow:true})
                }}>
                    <div className={styles.sub_litinss2}>
                      <div className={styles.sub_litinsstime}>{this.renderDate(this.state.checkDate)}</div>
                      <div>{this.state.checkTime}</div>
                    </div>
                    {/*<Icon type="right" color={"#C7C7C7"} size={"s"}/>*/}
                    <img src={'./img/in.png'} className={styles.sub_inimg} alt=""/>
                </div>
              :
                <div className={styles.sub_lit2} onClick={() => {
                    this.setState({timeBoxShow:true})
                }}>
                  <div>
                      请选择取衣时间
                  </div>
                      {/*<Icon type="right" color={"#C7C7C7"} size={"s"}/>*/}
                      <img src={'./img/in.png'} className={styles.sub_inimg} alt=""/>
                </div>
              }
          </List>
        </div>

          <div className={styles.sub_center}>商品信息</div>
          <List className="my-list">
              <div className={styles.sub_imgall} onClick={() => {this.props.history.push('/Laundry_details')}}>
                  <div>
                    {imgs}
                  </div>
                  <div className={styles.sub_imgrig}>
                     <span className={styles.sub_yu}>共{shengyu}件</span>
                     {/*<Icon type="right" color={"#C7C7C7"} size={"s"}/>*/}
                     <img src={'./img/in.png'} className={styles.sub_inimg} alt=""/>
                  </div>
              </div>
          </List>

          <div className={styles.sub_bei} onClick={()=>{
              this.setState({remarkShow:!this.state.remarkShow})
            }}>
            <div className={styles.sub_beitxt}>订单备注</div>
            <div className={styles.sub_beidown}>
              <span className={styles.sub_beitxt2}>{panelTextSS}</span>
              <img src={'./img/in.png'} className={styles.sub_inimg2} alt=""/>
            </div>
          </div>
          {this.state.remarkShow?
          <div className={styles.textaout}>
           <TextareaItem
                  onChange={(e)=>{
                      let ss = e
                      //  let isT = this.checkStr(ss)
                      //   if(!isT){
                      //     ss = this.replaceStr(ss)
                      //   }
                        this.setState({remark:ss,panelText:ss})
                  }}
                        ref="textareaNow"
                        rows={5}
                        className={styles.texta} placeholder='有问题请填写备注' value={this.state.panelText} />
          </div>
          :
          null
          }


          <div className={styles.sub_center2}>
              <div>运费
                {deliveryFee.postageMoney!==0 ?
                sumM >= deliveryFee.postageMoney?
                <span className={styles.sub_txt1}>（满{deliveryFee.postageMoney}元）</span>
                :<span className={styles.sub_txt1}>（未满{deliveryFee.postageMoney}元）</span>
                :null
                }
              </div>
              {sumM >= deliveryFee.postageMoney?
                <div className={styles.sub_txt}>免运费</div>
                :<div className={styles.sub_txt}>{deliveryFee.basicMoney}元</div>
              }
          </div>
     </div>


        {/*bottom*/}
        <div className={styles.sub_bot}>
          <div className={styles1.sub_lefbot}>
            <span className={styles.sub_text}>共<span className={styles.sub_tspan}>{shengyu}</span>件衣物</span>

            <div>
              {sumM >= deliveryFee.postageMoney?
                <div className={styles.sub_lefal}>总计：￥{sumM}</div>
                :<div className={styles.sub_lefal}>总计：￥{add(sumM,deliveryFee.basicMoney)}</div>
              }
              {sumM >= deliveryFee.postageMoney?
              <div className={styles.sub_text2}>免运费</div>
              :<div className={styles.sub_text2}>含{deliveryFee.basicMoney}元运费</div>
              }
            </div>

          </div>

          <button className={styles.sub_rigbut} onClick={this.place.bind(this)}>
            确认下单
         </button>
        </div>
      </div>
    )
  }
  place(){
    //const { dispatch } = this.props
    let businessId = getData("businessId");
    let user = JSON.parse(getData("userInfo"));
    let shops = JSON.parse(getSessionData("shop-dd-shops"))
    console.log(this.state.checkTime)
    if(!this.state.userAddress){
      alert("请填写地址")
      return
    }
    if(this.state.checkDate==""){
      alert("请填写取衣时间")
      return
    }
    if(this.state.checkTime!=""){
      let now = new Date()
      let myDate = moment(now).format("YYYY-MM-DD HH:mm")
      let tagTime = moment(this.state.checkDate).format("YYYY-MM-DD")+" "+this.state.checkTime.split("-")[1]
      console.log(myDate+"-----"+tagTime)
      let nnn = moment(tagTime).valueOf() //标签时间
      let mmm = moment(myDate).valueOf()//当前时间
      console.log(mmm+"-----"+nnn)
      if(nnn < mmm){
        alert("请重新选择取衣时间")
        return
      }
    }
    let isT = this.checkStr(this.state.remark)
    if(!isT){
      return
    }
    let isT2 = this.checkStrs(this.state.comment)
    if(!isT2){
      return
    }

    window.YLJsBridge.call(
      'bindStateDetection',
      {},
      (data)=>{
        if(data.code===0){
          console.log(data)
          let vv 
          if(isIOS()){
            vv = data.value
          }else{
            vv = JSON.parse(data.value)
          }
          console.log("========++++++========")
            if(vv.isBind){
              axios.post(API_HOST+"/app/order/initOrder", {
                agentsId:getAgentsId(),
                userId:user.userId,
                purchaserName:this.state.userAddress.name,
                purchaserPhone:this.state.userAddress.mobile,
                purchaserAddress:this.state.userAddress.address + this.state.userAddress.houseNumber,
                purchaserSex:this.state.userAddress.gender,
                serviceDate:this.state.checkDate,
                takeTime:this.state.checkTime,
                orderRemark:this.state.remark,
                shoppingCartDTO:{
                  businessId:businessId,
                  commodityLists:shops
                }
              }).then((res) => {
                console.log(res)
                if(res.data.code==="10000"){
                  //批量删除购物车
                  let shopCoreKeys = ""
                  shops.forEach((item,index)=> {
                    shopCoreKeys += (item.shoppingCartKey + ",")
                    if(index===shops.length-1) shopCoreKeys += item.shoppingCartKey
                  })
                  axios.post(API_HOST+"/app/shoppingCart/deleteShoppingCart", {shoppingCartKeys:shopCoreKeys})
                  //下单成功
                  let payOrderId = res.data.data.orderId
                  let orderNum = res.data.data.orderNum
                  addSessionData("myOrderId",payOrderId)//成功后保存订单id到session
                  window.YLJsBridge.call(
                    'pay',
                    {orderId:orderNum},
                    (data)=>{
                      console.log("=========")
                      console.log(data)
                      this.props.history.replace({
                        pathname:"/Mine_details",
                      })
                    }
                  )
                }else{
                  if(res.data.data!=="" && res.data.data !==null){
                    alert(res.data.data)
                  }else{
                    alert(res.data.msg)
                  }
                }
              })
            }else{
              alert("请绑定您的手机号，以完成下单")
            }
        }else{
          alert("获取绑定状态失败")
        }
      }
    )


  }

  checkStr(val){ 
    var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im,
    regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
    if(regEn.test(val) || regCn.test(val)) {
        alert("备注不能包含特殊字符.");
        return false;
    }else{
      return true;
    }

  }

  checkStrs(val){ 
    var regEn = /[\ud800-\udbff][\udc00-\udfff]/g;
    if(regEn.test(val)) {
        alert("备注不能包含表情.");
        return false;
    }else{
      return true;
    }
  }

  replaceStr(val){
    var reg = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]"); 
    var rs = ""; 
    for (var i = 0, l = val.length; i < val.length; i++) { 
        rs = rs + val.substr(i, 1).replace(reg, ''); 
    } 
    return rs; 
  }


  componentDidMount(){
    console.log(this.props)
  }
}
